<template>
  <div class="userBox">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 主体部分使用卡片 -->
    <el-card class="box-card">
      <!-- 通过flex属性实现弹性布局,span默认占24份 -->
      <el-row type="flex">
        <el-col :span="12">
          <div class="grid-content bg-purple" style="text-align: left">
            <el-input
              clearable
              placeholder="请输入内容"
              class="input-with-select"
              v-model.trim="params.query"
              @clear="getSearchUsers"
              @keydown.native.enter="getSearchUsers"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getSearchUsers"
              ></el-button>
            </el-input>
          </div>
        </el-col>

        <el-col :span="3">
          <div class="grid-content bg-purple">
            <el-row type="flex">
              <el-col :span="1"></el-col>
              <el-col :span="19">
                <el-button type="primary" @click="dialogFormVisible = true"
                  >添加用户</el-button
                >
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>

      <el-table :data="tableData" border style="width: 100%  margin-top:10px">
        <el-table-column type="index" width="50"> </el-table-column>
        <!-- prop为对应列内容的字段名 -->
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <!-- 通过作用域插槽的scope拿到当前行用户的数据 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeUserState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="mg_state" label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              class="operate"
              @click="editUser(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              class="operate"
              @click="deleteUser(scope.row)"
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              class="operate"
              @click="allocatedLimits(scope.$index, scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pagenum"
        :page-sizes="[1, 2, 5, 10, 50]"
        :page-size="params.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalpage"
      >
        <!-- page-sizes为可选每页显示数据 -->
        <!-- page-size为每页实际展示数据 -->
        <!-- :total绑定了请求回来的数据总条数 -->
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <!-- 通过点击添加按钮设置dialogFormVisible属性为true 来展示该对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form :model="form" ref="form" :rules="rules">
        <el-form-item
          label="用户名"
          prop="username"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="用户密码"
          prop="password"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="用户邮箱"
          prop="email"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改信息对话 -->
    <el-dialog title="编辑用户" :visible.sync="editVisible">
      <el-form :model="editForm" ref="editForm" :rules="rules">
        <el-form-item
          label="用户名"
          prop="username"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="editForm.username"
            autocomplete="off"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="用户邮箱"
          prop="email"
          :label-width="formLabelWidth"
        >
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
          :label-width="formLabelWidth"
        >
          <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserData">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配权限弹框 -->
    <el-dialog title="分配角色" :visible.sync="dialogFormVisibleLimits">
      <el-form :model="limitsForm">
        <el-form-item label="当前的用户:" :label-width="formLabelWidth">
          <el-tag type="success">{{ limitsForm.username }}</el-tag>
          <!-- <el-input v-model="formLimits.name" autocomplete="off"></el-input> -->
        </el-form-item>
        <el-form-item label="当前的角色:" :label-width="formLabelWidth">
          <el-tag type="success">{{ limitsForm.role_name }}</el-tag>
          <!-- <el-input v-model="formLimits.name" autocomplete="off"></el-input> -->
        </el-form-item>
        <el-form-item label="分配新角色:" :label-width="formLabelWidth">
          <el-select v-model="roleValue" placeholder="请选择">
            <el-option
              v-for="item in rolesUsers"
              :key="item.value"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleLimits = false">取 消</el-button>
        <el-button type="primary" @click="setUsersRoles">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUsers,
  getChangeUserState,
  getAddUsers,
  getDeleteUsers,
  getUpdateUsers,
  getRoles,
  getUsersRole,
} from "../../api/index";

export default {
  data() {
    var validateMobile = (rule, value, callback) => {
      let regMobile = /^[1]([3-9])[0-9]{9}$/;
      if (!regMobile.test(value)) {
        callback(new Error("手机号码输入不符合规范"));
      } else {
        callback();
      }
    };

    return {
      tableData: [],
      totalpage: 0, //总页数
      // 分页数据
      params: {
        query: "",
        pagenum: 1,
        pagesize: 10,
      },
      // 弹框数据
      dialogFormVisible: false,
      form: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      formLabelWidth: "200px",
      // 添加数据前端验证规则
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
        ],

        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
        ],
        email: [{ required: true, message: "请输入用户邮箱", trigger: "blur" }],
        mobile: [{ validator: validateMobile, trigger: "blur" }],
      },
      // 修改信息弹框数据
      editVisible: false,
      editForm: {
        username: "",
        email: "",
        mobile: "",
      },
      // 分配权限数据
      dialogFormVisibleLimits: false,
      limitsForm: {
        username: "",
        role_name: "",
      },
      rolesUsers: [], // 用户角色初始数据
      roleValue: "", // 定义角色的id值
    };
  },
  created() {
    this.getUsersList();
  },
  methods: {
    // 获取指定数据的用户列表
    async getUsersList() {
      let {
        data: { users, pagenum, total },
      } = await getUsers(this.params);
      // console.log(data);
      this.tableData = users;
      this.params.pagenum = pagenum;
      this.totalpage = total;
    },
    // 分页功能
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      // 每页显示数据的改变即为向后台发送数据请求,得到相应的页数和数据量然后渲染
      this.params.pagesize = val;
      this.getUsersList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.params.pagenum = val;
      this.getUsersList();
    },
    // 搜索功能
    getSearchUsers() {
      this.getUsersList();
    },
    // 改变用户状态
    async changeUserState(data) {
      let res = await getChangeUserState({ id: data.id, type: data.mg_state });
      // console.log(res)
      let {
        meta: { msg, status },
      } = res;
      if (status == 200) {
        this.$message({ type: "success", message: msg });
        // 状态绑定的是前台的信息,更新状态后刷新页面,确保后台状态已修改
        this.getUsersList();
      }
    },
    // 添加用户
    async addUsers() {
      let success = await this.$refs["form"].validate().catch(() => {});
      if (!success) return false;

      let {
        meta: { msg, status },
      } = await getAddUsers(this.form);
      if (status == 201) {
        // 添加数据信息成功则弹出提示信息并隐藏对话框
        this.$message.success(msg);
        this.dialogFormVisible = false;
        // 重新渲染页面
        this.getUsersList();
      } else {
        this.$message.error(msg);
      }
    },
    // 删除用户
    async deleteUser(data) {
      let res = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {});

      if (res != "confirm") return this.$message("取消操作");

      let {
        meta: { msg, status },
      } = await getDeleteUsers(data.id);
      if (status == 200) {
        this.$message.success(msg);
        this.getUsersList();
      } else {
        this.$message(msg);
      }
    },
    // 点击编辑用户的按钮
    editUser(data) {
      this.editVisible = true;
      this.editForm = data;
    },
    // 编辑信息提交
    async editUserData() {
      let success = await this.$refs["editForm"].validate().catch(() => {});
      if (!success) return false;
      // 发送修改信息请求
      let {
        meta: { msg, status },
      } = await getUpdateUsers(this.editForm);
      if (status == 200) {
        this.$message.success(msg);
        this.editVisible = false;
        this.getUsersList();
      } else {
        this.$message.error(msg);
      }
    },
    // 分配权限
    async allocatedLimits(index, item) {
      // 调用获取角色函数,获取角色列表
      let { data: rolesList } = await getRoles();
      // 对角色列表进行处理,保留用户id和角色名
      let newArr = rolesList.reduce((preVal, currentItem) => {
        return [
          ...preVal,
          { id: currentItem.id, roleName: currentItem.roleName },
        ];
      }, []);
      // 将弹框绑定的需要显示的数据与请求的数据联系
      this.rolesUsers = newArr;

      //1 打开弹框
      this.dialogFormVisibleLimits = true;
      // 弹框数据为当前列数据
      this.limitsForm = item;
    },
    async setUsersRoles() {
      // console.log(this);
      // 点击确认按钮.真正地向后台发送修改角色的请求
      console.log(this.limitsForm.id, this.roleValue);
      let res = await getUsersRole({
        id: this.limitsForm.id,
        rid: this.roleValue,
      });
      let {
        meta: { msg, status },
      } = res;
      if (status != 200) return this.$message.error(msg);
      this.$message.success(msg);
      this.getUsersList();
      this.dialogFormVisibleLimits = false;
    },
  },
};
</script>

<style scoped lang="less">
.box-card {
  width: 100%;
  max-height: 820px;
  overflow: auto;
}

.userBox {
  padding-left: 20px;
}

.el-breadcrumb {
  font-size: 12px;
  background-color: initial;
  margin-bottom: 0;
}

.el-table {
  margin-top: 20px;
  max-height: 650px;
  overflow: auto;
}

.operate {
  width: 45px;
  height: 25px;
  text-align: center;
  line-height: 25px;
  padding: 0;
  i {
    vertical-align: top;
  }
}

.el-pagination {
  margin-top: 15px;
  text-align: center;
}
</style>
